from app.api.system.schemas import role_schema
from app.models.system import Role, RolePermission
from app.utils.curd_base import ModelCRUD
from sqlalchemy.orm import Session
from fastapi.encoders import jsonable_encoder
from sqlalchemy import not_


class CRUDRole(ModelCRUD):
    model = Role

    @staticmethod
    def serializer(queryset, only: tuple = (), date_format: str = None, datetime_format: str = None,
                   time_format: str = None):

        li = []
        for instance in queryset:
            data_dict = instance.to_dict(only=only, date_format=date_format, datetime_format=datetime_format,
                                         time_format=time_format)
            data_dict['permission'] = [
                {"name": permission.permission.name, "id": permission.permission_id} for permission in instance.permission
            ]
            # print(instance.permission)
            li.append(data_dict)
        return li


crud_role = CRUDRole()


class CRUDRolePermission(ModelCRUD):

    model = RolePermission

    def batch_create(self, db: Session, *, data: role_schema.SetRolePermission):
        req_data = jsonable_encoder(data)
        permission_list = req_data.pop('permission', [])
        role = req_data.get('role')
        for permission in permission_list:
            instance = self.model(permission_id=permission, role_id=role)  # type: ignore
            db.add(instance)
        db.commit()
        return True

    def modify(self, db: Session, *, data: role_schema.SetRolePermission):
        req_data = jsonable_encoder(data)
        permission_list = req_data.pop('permission', [])
        role = req_data.get('role')

        queryset = db.query(self.model).filter(self.model.role_id == role)  # type: ignore
        for permission_id in permission_list:
            if not queryset.filter(self.model.permission_id == permission_id).first():
                instance = self.model(permission_id=permission_id, role_id=role)  # type: ignore
                db.add(instance)
        del_queryset = queryset.filter(not_(self.model.permission_id.in_(permission_list)))
        del_queryset.delete()
        db.commit()
        return True


crud_role_permission = CRUDRolePermission()





